package org.mineground.commands.irc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.jibble.pircbot.Colors;
import org.jibble.pircbot.User;
import org.mineground.Main;
import org.mineground.handlers.irc.CommandExecutor;
import org.mineground.handlers.irc.UserLevel;
import org.mineground.player.MinegroundPlayer;
import org.mineground.player.Supported;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @file Value.java (2012)
 * @author Daniel Koenen
 * 
 */
public class Value implements CommandExecutor {
    private static final Logger ExceptionLogger = LoggerFactory.getLogger(Value.class);
    
    @Override
    public void onCommand(User sender, UserLevel level, String channel, String command, String[] args) {
        if (level.compareTo(UserLevel.IRC_SOP) < 0) {
	    return;
        }
        
        if (args.length < 2) {
            StringBuilder outputString = new StringBuilder();
            List<String> supportedList = new ArrayList<String>(Supported.getSupportedKeys().keySet());
            
            outputString.append(Colors.BLACK);
            outputString.append(Colors.BOLD);
            outputString.append("Supported values: ");
            outputString.append(Colors.NORMAL);
            
            for (String supportedName : supportedList) {
                outputString.append(supportedName);
                outputString.append(", ");
            }
            
            Main.getInstance().getIRCHandler().sendMessage(channel, outputString.substring(0, outputString.length() - 2));
            Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Usage:" + Colors.NORMAL + " !value [player name] [get/set]");
	    return;
	}
        
        String playerName = args[0];
        String valueCommand = args[1];
        
        if (valueCommand.equalsIgnoreCase("get")) {
            if (args.length < 3) {
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Usage:" + Colors.NORMAL + " !value [player name] [get] [key]");
                return;
            }
            
            String valueKey = args[2];
            
            if (!Supported.getSupportedKeys().containsKey(valueKey)) {
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Error: Invalid key, please see '!value' for a list of all keys.");
                return;
            }
            
            int profileId = getProfileId(playerName);
            
            if (profileId == MinegroundPlayer.INVALID_PROFILE_ID) {
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Error: Can't find that player.");
                return;
            }
            
            try {
                String valueTable = Supported.getSupportedKeys().get(valueKey);
                final String queryString = "SELECT " + valueKey + " FROM " + valueTable + " WHERE player_id = ?";
                PreparedStatement queryStatement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement(queryString);
                queryStatement.setInt(1, profileId);
                queryStatement.execute();
                
                ResultSet queryResult = queryStatement.getResultSet();
                queryResult.next();
                Object theResult = queryResult.getObject(1);
                
                StringBuilder outputBuilder = new StringBuilder();
                outputBuilder.append(Colors.TEAL);
                outputBuilder.append("Value ");
                outputBuilder.append(Colors.NORMAL);
                outputBuilder.append(valueKey);
                outputBuilder.append(Colors.TEAL);
                outputBuilder.append(" for player ");
                outputBuilder.append(Colors.NORMAL);
                outputBuilder.append(playerName);
                outputBuilder.append(Colors.TEAL);
                outputBuilder.append(" is ");
                outputBuilder.append(Colors.NORMAL);
                outputBuilder.append(theResult.toString());
                
                Main.getInstance().getIRCHandler().sendMessage(channel, outputBuilder.toString());
            }
            
            catch (Exception exception) {
                ExceptionLogger.error("Exception caught", exception);
            }
        }
        
        if (valueCommand.equalsIgnoreCase("set")) {
            if (args.length < 4) {
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Usage:" + Colors.NORMAL + " !value [player name] [set] [key] [value]");
                return;
            }
            
            String valueKey = args[2];
            String value = args[3];
            
            if (!Supported.getSupportedKeys().containsKey(valueKey)) {
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Error: Invalid key, please see '!value supported' for a list of all keys.");
                return;
            }
            
            int profileId = getProfileId(playerName);
            
            if (profileId == MinegroundPlayer.INVALID_PROFILE_ID) {
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Error: Can't find that player.");
                return;
            }
            
            try {
                String valueTable = Supported.getSupportedKeys().get(valueKey);
                final String queryString = "UPDATE " + valueTable + " SET " + valueKey + " = ? WHERE player_id = ?";
                PreparedStatement queryStatement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement(queryString);
                queryStatement.setObject(1, value);
                queryStatement.setInt(2, profileId);
                queryStatement.execute();
                
                Main.getInstance().getIRCHandler().sendMessage(channel, Colors.TEAL + "Value has been updated.");
            }
            
            catch (Exception exception) {
                ExceptionLogger.error("Exception caught", exception);
            }
        }
    }
    
    private int getProfileId(String playerName) {
        int profileId = MinegroundPlayer.INVALID_PROFILE_ID;
        
        try {
            PreparedStatement queryStatement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement("SELECT player_id FROM lvm_players WHERE login_name = ? LIMIT 1");
            ResultSet queryResult;

            queryStatement.setString(1, playerName);
            queryStatement.execute();
            queryResult = queryStatement.getResultSet();

            if (queryResult.next()) {
                profileId = queryResult.getInt(1);
            }

            queryStatement.close();
        } 
        
        catch (Exception exception) {
            ExceptionLogger.error("Exception caught", exception);
        }
        
        return profileId;
    }
}
